<?php

$ip_info = detectIPInfo();
echo json_encode($ip_info);

function detectIPInfo() {
    $ip_parser = array();
    $ip = $_SERVER ['REMOTE_ADDR'];
    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip;
    $content = file_get_contents($url);
    $info = explode("=", $content);
    $json = $info [1];

    if (isset($json) && $json != "") {
        $json = str_replace(";", "", $json);
        $txt = json_decode($json, true);
        $carrier = $txt['isp'];
    } else {
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=" . $ip;
        $content = file_get_contents($url);

        if (mb_check_encoding($content, "utf-8") != 1) {
            if (mb_check_encoding($content, "gbk") == 1) {
                $content = mb_convert_encoding($content, "utf-8", "gbk");
            } else {
                $content = mb_convert_encoding($content, "utf-8");
            }
        }

        $info = preg_split("/[\s,]+/", $content);

        $carrier = $info [6];
    }
    if ($carrier == "电信") {
        $carrier = "telecom";
    } else if ($carrier == "联通") {
        $carrier = "unicom";
    } else {
        $carrier = "telecom";
    }
    $ip_parser['isp'] = $carrier;
    $ip_parser['ip'] = $ip;
    return $ip_parser;
}

?>
